import QtQuick 1.1
import com.nokia.meego 1.0
import meegim 1.0
import "main.js" as Engine

PageStackWindow {
    id: main

    showStatusBar: false
    showToolBar: false

    property string loadPage: "RosterPage.qml"
    property variant mainViewItem

    //property string chatAvatar: "" //аватар для которого открыто окно чата

    /* окно редактирование аккаунта */
    property string accJid: ""
    property string accPass: ""
    property string accResource: ""
    property string accHost: ""
    property string accPort: ""
    property bool accManualHostPort: false
    property bool accDefault: false

    signal statusChanged
    property string statStatusText: xmppClient.statusText
    signal statusTextChanged

    property int orPortrait: PageOrientation.LockPortrait
    property int orAuto: PageOrientation.Automatic
    property int appOrientation: PageOrientation.LockPortrait

    property bool requestMyVCard: false // используется для запроса своей vCard


    MyTheme { id: mytheme }

    initialPage: MainView {
    }


    XmppClient {
        id: xmppClient

        onMessageReceived: {
            //console.log("==> QML: a message received: " + bareJidLastMsg)
            //при открывании и закрытии окна чата сообщения будут сбрасываться
            if( (main.loadPage.indexOf("RosterPage.qml")+1) && (settings.notifyMessage == true) ) {
                createInfoPanel( "qrc:/qml/images/msg_recv.png", "Message from \n" + bareJidLastMsg, 3000, "lightblue" )
            }
            //FIXME: лажа со звуковыми оповещениями
            //if( (bareJidLastMsg != xmppClient.myBareJid) && (!(main.loadPage.indexOf("MucPage.qml")+1)) ) {
            //console.log("*** "+bareJidLastMsg + "|" + xmppClient.myBareJid + "|" + toBareJid + "|" + fromBareJid )
            //if( (xmppClient.myBareJid == toBareJid) && (!(fromBareJid.indexOf("conference")+1)) ) {
            if( (xmppClient.myBareJid == toBareJid) && (muc.jidRoom != fromBareJid) )
            {
                if( !(fromBareJid.indexOf("conference")+1) )
                {
                    notify.notifyMessageRecv()
                    //console.log("***<<< MESSAGE RECEIVED >>>***")
                    /*meventfeed.icon = ""
                    meventfeed.title = "MeegIM"
                    meventfeed.body = "You have received a message from " + fromBareJid
                    meventfeed.pushEvent()*/
                }
            }
        }

        onTypingChanged: {
            //console.log("==> QML: ["+ bareJid +"] is typing: [" + isTyping + "]" )
            if( (main.loadPage.indexOf("RosterPage.qml")+1) && (settings.notifyTyping == true) ) {
                if( isTyping ) {
                    createInfoPanel( "qrc:/qml/images/bar_edit.png", bareJid + "\nis typing", 2000, "lightblue" )
                } else {
                    createInfoPanel( "qrc:/qml/images/bar_edit.png", bareJid + "\nhas stopped typing", 2000, "lightblue" )
                }
            }
        }

        onConnectingChanged: {
            if( (stateConnect == XmppClient.Connecting) && (settings.notifyConnection == true) ) {
                createInfoPanel( "qrc:/qml/images/presence-unknown.png", "Connecting...", 1000, "lightblue" )
            } else if( (stateConnect == XmppClient.Connected)  && (settings.notifyOnline == true) ) {
                createInfoPanel( "qrc:/qml/images/presence-online.png", "Online", 3000, "lightgreen" )
            } else if( (stateConnect == XmppClient.Disconnected)  && (settings.notifyOffline == true) ) {
                createInfoPanel(  "qrc:/qml/images/presence-offline.png", "Offline", 3000, "gray" )
            }
        }

        onStatusTextChanged: {
            console.log( "XmppClient::onStatusTextChanged:" + statusText )
            main.statusTextChanged()
        }

        onStatusChanged: {
            console.log( "XmppClient::onStatusChanged:" + status )
            main.statusChanged()
        }

        onVCardChanged: {
            xmppVCard.vcard = xmppClient.vcard //это действие перенесено в VCardPage.qml
        }

        onErrorHappened: {
            console.log("QML: Error: " + errorString )
            createInfoPanel(  "qrc:/qml/images/presence-unknown.png", "Error: "+errorString, 5000, "red" )
        }

        onPresenceJidChanged:
        {
            //TODO: Сюда вставлять извещения
            if( presenceBareJid != xmppClient.myBareJid ) {
                if( presenceTextStatus == "Offline" ) {
                    notify.notifyBuddyLogsOut()
                } else {
                    notify.notifyBuddyLogsIn()
                }
            }

            //console.log( "QML: XmppClient::onPresenceJidChanged: " +presenceBareJid + " / " + presenceTextStatus + " / " + presencePicStatus )
        }

        onSubscriptionReceived: {
            //console.log( "XmppClient::onSubscriptionReceived: [" + subscriptionJids + "]" )
            //createInfoPanel( "", "Subscription received \n from "+bareJid, 5000, "lightblue" )
        }
    } //XmppClient


    MeegIMSettings {
        id: settings
    }

    XmppVCard {
        id: xmppVCard
    }

    MSmiles {
        id: mainSmiles
        file: settings.smilesTheme
        onSmilesModelChanged: {
            console.log("QML: MSiles::onSmilesModelChanged: The model was changed.")
        }
    }


    /*------------( Multi user chats )------------*/
    property string invRoomJid: ""
    property string invInviterJid: ""
    property string invMyNickName:""
    XmppMuc {
        id: muc
        mucManager: xmppClient.mucManager
        nickName: xmppClient.myBareJid.substring( 0, xmppClient.myBareJid.indexOf('@') )
        onInvitationMucReceived: {
            invRoomJid = roomJid
            invInviterJid = inviterJid
            invMyNickName = nickName
            notify.notifyMessageRecv()
        } //onInvitationMucReceived
        onSubjectRoomChanged: {
            xmppClient.setMucSubject( muc.jidRoom, subject )
        }
        onMessageReceived: {
            var pos = textMessage.indexOf(":");
            if( pos > 0 ) {
                var pehapsNickName = textMessage.substring( 0, pos )
                if( pehapsNickName == muc.nickName ) {
                    notify.notifyChatSomeoneSaysMyName()
                    return
                }
            }
            if( nickName != muc.nickName ) {
                notify.notifyChatOthersTalk()
            }
        }
    }
    /*------------ ------------*/



    Component.onCompleted: {
        initAccount()
        Engine.clearInfoStack() //очистка стека инфо сообщений
    }

    property bool _existDefaultAccount: false
    function initAccount()
    {
        _existDefaultAccount = false
        for( var j=0; j<settings.accounts.count(); j++ )
        {
            if( settings.accIsDefault( j ) )
            {
                _existDefaultAccount = true
                xmppClient.myBareJid = settings.accGetJid( j );
                xmppClient.myPassword = settings.accGetPassword( j );
                xmppClient.resource = settings.accGetResource( j );

                if( settings.accIsManuallyHostPort( j ) ) {
                    xmppClient.host = settings.accGetHost( j  );
                } else {
                    xmppClient.host = "";
                }

                if( settings.accIsManuallyHostPort( j ) ) {
                    xmppClient.port = settings.accGetPort( j  );
                } else {
                    xmppClient.port = 0;
                }

                console.log("QML: main::initAccount():" + xmppClient.myBareJid + "/" + xmppClient.resource);
                break;
            }
        }
    }


    /**************( info panels )*************/
    Component {
        id: infoPanelComponent
        TopInfoPanel {
            id: infoPanel
            onClosed: {
                Engine.removeInfoPanel( infoPanel )
            }
        }
    }

    function createInfoPanel( icon, message, time_ms, color )
    {
        Engine.infoMessage( infoPanelComponent,  icon, message, time_ms, color )
    }

    //-----------

    /*Component {
        id: infoPanelSubcrRecvComponent
        TopInfoPanel {
            id: subscrRecvPanel
            onClicked: {

            }
        }
    }*/

    /**************(* notify *)**************/
    //property variant notify
    Notify {
        id: notify
    }

    /*MEventFeed {
        id: meventfeed
    }*/


}
